import searchApi from '@/api/searchApi'
import { AxiosResponse } from 'axios'
import storage, { OPTION } from '@/utils/goodStorageUtil'
import { defineStore } from 'pinia'
export const initKeyWordVal = '请输入搜索的图书关键字'

export default defineStore('searchStore', {
  state: () => {
    return initState
  },
  getters: {
    getKeyWord(state) {
      return state.keyWord
    },
    getHistoryKeywordList(state) {
      return state.historyKeywordList.length > 0 ? state.historyKeywordList : storage.get('historyKeywordList')
    },
    getHistoryKeyWordObjList(state): HistoryKeyWord[] {
      return state.historyKeyWordObjList.length > 0 ? state.historyKeyWordObjList : storage.get('historyKeyWordObjList')
    },
    getAutoCompKeyword(state) {
      return state.autoCompKeyword.length > 0 ? state.autoCompKeyword : storage.get('autoCompKeyword')
    },
  },
  actions: {
    storeAutoCompKeyword(autoCompKeyword: string) {
      this.autoCompKeyword = autoCompKeyword
      storage.set('autoCompKeyword', autoCompKeyword)
    },
    async getHistoryList() {
      const res = await searchApi.getHistoryKeyWordsList()
      this.historyKeywordList = res.data
      storage.set('historyKeywordList', this.historyKeywordList, OPTION.NONE)
    },
    storeKeyWord(keyWord: string = '') {
      this.keyWord = keyWord
    },
    async searchKeywords(key: string) {
      const keywordList: AxiosResponse<KeyWord[]> = await searchApi.searchKeyWords(key)
      this.keyWordList = keywordList.data
    },
    async addOrUpdateHistoryKeyword(keyword: KeyWord) {
      const result: AxiosResponse<number> = await searchApi.addOrUpdateHistoryKeyword(keyword.keyword)
      if (result.data > 0) {
        const item = { id: keyword.id, historykeyword: keyword.keyword }
        const historyKeywordList = storage.set('historyKeywordList', item, OPTION.ADDAPPENDOBJTOARR, 'id', keyword.id)
        this.historyKeywordList = historyKeywordList
      }
    },
    async searchDecovery() {
      const historyKeyWordObjList: AxiosResponse<HistoryKeyWord[]> = await searchApi.searchDecovery()
      this.historyKeyWordObjList = historyKeyWordObjList.data
      storage.set('historyKeyWordObjList', historyKeyWordObjList.data)
    },
    async deleteHistoryKeyWord(id: number) {
      await searchApi.deleteHistoryKeyWord(id)
      await this.getHistoryList()
    },
  },
})

export interface KeyWord {
  id: number
  keyword: string
}
export interface HistoryKeyWord {
  id: number
  historykeyword: string
  clickcount: number
}

type initStateType = {
  keyWord: string
  keyWordList: KeyWord[]
  historyKeywordList: string[]
  historyKeyWordObjList: HistoryKeyWord[]
  autoCompKeyword: string
}
const initState: initStateType = {
  keyWord: initKeyWordVal,
  keyWordList: [],
  historyKeywordList: [],
  historyKeyWordObjList: [],
  autoCompKeyword: '',
}
